package lk.icta.sms;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.namespace.QName;
import javax.xml.soap.*;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import java.util.Set;
import java.util.TreeSet;

/**
 * @author Supun Viraj Rathnayaka
 */
public class SMSSOAPHandler implements SOAPHandler<SOAPMessageContext>{
    private static final Logger logger = LoggerFactory.getLogger(SMSSOAPHandler.class);
    @Override
    public Set<QName> getHeaders() {
        return new TreeSet();
    }

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        Boolean outboundProperty =(Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (outboundProperty.booleanValue()) {
            try {
                SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();

                SOAPFactory factory = SOAPFactory.newInstance();
                String prefix = "govsms";
                String uri = "http://govsms.icta.lk/";

                SOAPElement authData =factory.createElement("authData",prefix,uri);
                SOAPElement user =factory.createElement("user",prefix,uri);
                SOAPElement key =factory.createElement("key",prefix,uri);
                user.addTextNode("icta");
                key.addTextNode("g0v5ms123");
                authData.addChildElement(user);
                authData.addChildElement(key);

                /** Adding Customized Soap Header */
                SOAPHeader header = envelope.addHeader();
                header.addChildElement(authData);
            } catch (Exception e) {
               logger.debug("Exeption in handler: {}", e);
                e.printStackTrace();
            }
        }
        return true;
    }

    @Override
    public boolean handleFault(SOAPMessageContext soapMessageContext) {
        return true;
    }

    @Override
    public void close(MessageContext messageContext) {

    }
}
